package packet

import (
	"encoding/binary"
	"math"

	"gitee.com/ameise84/e3utils/bytes_buffer"
	"gitee.com/ameise84/e3utils/str_conv"
)

func UnPackBool(r bytes_buffer.Reader, order binary.ByteOrder, data *bool) bool {
	o, err := r.FetchLen(1)
	if err != nil {
		panic(err)
	}
	return o[0] > 0
}

func UnPackUint8(r bytes_buffer.Reader, order binary.ByteOrder) uint8 {
	o, err := r.FetchLen(1)
	if err != nil {
		panic(err)
	}

	return o[0]
}

func UnPackUint16(r bytes_buffer.Reader, order binary.ByteOrder) uint16 {
	o, err := r.FetchLen(2)
	if err != nil {
		panic(err)
	}
	return order.Uint16(o)
}

func UnPackUint32(r bytes_buffer.Reader, order binary.ByteOrder) uint32 {
	o, err := r.FetchLen(4)
	if err != nil {
		panic(err)
	}
	return order.Uint32(o)
}

func UnPackUint64(r bytes_buffer.Reader, order binary.ByteOrder) uint64 {
	o, err := r.FetchLen(8)
	if err != nil {
		panic(err)
	}
	return order.Uint64(o)
}

func UnPackUint(r bytes_buffer.Reader, order binary.ByteOrder) uint {
	return uint(UnPackUint64(r, order))
}

func UnPackInt8(r bytes_buffer.Reader, order binary.ByteOrder) int8 {
	return int8(UnPackUint8(r, order))
}

func UnPackInt16(r bytes_buffer.Reader, order binary.ByteOrder) int16 {
	return int16(UnPackUint16(r, order))
}

func UnPackInt32(r bytes_buffer.Reader, order binary.ByteOrder) int32 {
	return int32(UnPackUint32(r, order))
}

func UnPackInt64(r bytes_buffer.Reader, order binary.ByteOrder) int64 {
	return int64(UnPackUint64(r, order))
}

func UnPackInt(r bytes_buffer.Reader, order binary.ByteOrder) int {
	return int(UnPackUint64(r, order))
}

func UnPackFloat32(r bytes_buffer.Reader, order binary.ByteOrder) float32 {
	return math.Float32frombits(UnPackUint32(r, order))
}

func UnPackFloat64(r bytes_buffer.Reader, order binary.ByteOrder) float64 {
	return math.Float64frombits(UnPackUint64(r, order))
}

func UnPackString(r bytes_buffer.Reader, order binary.ByteOrder) string {
	n := UnPackInt(r, order)
	if n == 0 {
		return ""
	}
	bs := make([]byte, n)
	err := r.ReadLen(bs, n)
	if err != nil {
		panic(err)
	}
	return str_conv.ToString(bs)
}

func UnPackBytes(r bytes_buffer.Reader, order binary.ByteOrder) []byte {
	n := UnPackInt(r, order)
	if n == 0 {
		return []byte{}
	}
	bs := make([]byte, n)
	err := r.ReadLen(bs, n)
	if err != nil {
		panic(err)
	}
	return bs
}
